package com.crl.core.module
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	public class ModulesMediator extends EventDispatcher
	{
		private var modulesMap:Dictionary;
		
		public function ModulesMediator()
		{
			initializeMediator();
		}
		protected function initializeMediator() : void
		{
			modulesMap = new Dictionary();
		}
		
		public function registerModule(module:IModule):void{
			modulesMap[module.name]=module;
			if(module.onRegister()==false){
				return;
			}
			var commands:Vector.<String>=module.getEventList();
			if(commands==null)return;
			
			for each(var command:String in commands){
				this.addEventListener(command,module.handler);
			}
		}
		
		/**
		 * 
		 * @param moduleName
		 * @return 
		 * 
		 */		
		public function removeModule( moduleName : String ) : IModule
		{
			var module : IModule = modulesMap[ moduleName ] as IModule;
			if( module==null ){
				return null;
			}
			
			var commands:Vector.<String>=module.getEventList();
			if(commands){
				for each(var command:String in commands){
					this.removeEventListener(command,module.handler);
				}
			}
			
			delete modulesMap[ moduleName ];
			module.onRemove();
			
			return module;
		}
		
		
		public function hasModule( moduleName : String ) : Boolean
		{
			var module : IModule = modulesMap[ moduleName ] as IModule;
			if( module )
			{
				return true;
			}
			
			return false;
		}
		
		
		/**
		 * 默认为弱引用; 
		 * @param type
		 * @param listener
		 * @param useCapture
		 * @param priority
		 * @param useWeakReference
		 * 
		 */		
		override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=true) : void{
			super.addEventListener(type,listener,useCapture,priority,useWeakReference);
		}
		
	}
}